

	package controllers;

	import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import model.SubscriptionRequestModel;
import model.TaarifModel;
import model.TaarifRequestModel;
import model.UserPermissions;
import view.BuyaSubcriptionDetailsGUI;
import view.BuyaSubscriptionGUI;
import client.CliMessage;


		/**
		 * This Class is a BuyaSubscriptionController which extends AbstractController
		 * @author Tal 
		 *
		 */

		public class BuyaSubscriptionController extends AbstractController implements IValidateInput
		{	
					private BuyaSubscriptionGUI  SubView;
					private TaarifRequestModel tarRequestModel;
					private UserPermissions up;
					private ArrayList<String> subGroup=null;
					
					/**
					 * This is Buy a Subscription controller constructor.
					 * @param SubView is a Buy a Subscription window GUI instance.
					 * @param tarRequestModel is a TaarifRequestModel Model instance.
					 */
					public BuyaSubscriptionController(  BuyaSubscriptionGUI  SubView, TaarifRequestModel tarRequestModel,UserPermissions up) 
					{
						super(SubView,tarRequestModel);
						this.SubView = SubView;
						this.tarRequestModel = tarRequestModel;
						this.up=up;
					
					}
					
					@Override
					public boolean validateInput() 
					{
						int index=SubView.getItemSelectedIndex();
						
							if(index<1)
							{
								
								SubView.displayWrnMessage("You MUST Choose Package Before Purchase ");
								
								return false;
							}
							
							if (index==2)
							{
								int indx2=SubView.getItemSelectedIndex2();
								if (indx2<1)
								{
									SubView.displayWrnMessage("You MUST To Choose Location  ");
									
									return false;
								}
							}
						return true;
						
					}
					
					/**
					 * This is setButton method-this method add listeners to buttons in Buy a Subscription window.
					 * 
					 */
					
					private void setButton()
					{
						
						SubView.addPurchaseActionListener(new PurchaseListener(this,SubView,up));
					}
								
					
					/**
					 * Inner class that handles when Purchase Button Pressed , extends AbstractListener
					 * @author Tal
					 *
					 */
					
					class PurchaseListener extends AbstractListener
					{//
						private BuyaSubscriptionGUI  SubView;
						private BuyaSubscriptionController previusObserver;
						private UserPermissions up;
						
						public PurchaseListener(BuyaSubscriptionController previusObserver,  BuyaSubscriptionGUI  SubView,UserPermissions up)
						{
							this.SubView=SubView;
							this.previusObserver=previusObserver;
							this.up=up;
						}
						
						@Override
						public void actionPerformed(ActionEvent arg0) 
						{
							if(!validateInput())
								return;
	                               
							//create a new buy sub details controller
							BuyaSubcriptionDetailsGUI buySubDetView = new BuyaSubcriptionDetailsGUI();
							SubscriptionRequestModel subreqModel = new SubscriptionRequestModel();
							
							//init  sub request 
							subreqModel.setUID(up.getCurrUserID());
							
							subreqModel.setGID(SubView.getItemSelectedID());
							int index=SubView.getItemSelectedIndex();
							
							if (index!=2)//not daily
							      subreqModel.setLocation(0);
							else
								 subreqModel.setLocation(SubView.getItemSelectedIndex2());
							
							System.out.println(SubView.getItemSelectedIndex2());
							System.out.println("uid:"+up.getCurrUserID()+"  gid:"+SubView.getItemSelectedID());
							
							//remove components
							subGroup.removeAll(subGroup);
							tarRequestModel.RemoveTaarifRequest();
							SubView.clearFields();
							SubView.disposeCombo();
							SubView.setCombo();
							
							BuyaSubscriptionDetailsController buySubDetCon = new BuyaSubscriptionDetailsController(buySubDetView,subreqModel);
									
							
							
							//add observer to new controller and delete the rest
							setCurrentObserver(buySubDetCon);						
							
							//add a listener to "back" button in buy sub  window
							setBackListener(previusObserver,buySubDetView);
										
						}
					}



					@Override
					public void handleDBRequestSuccess()
					{
						SubView.displayWrnMessage("Subscription Requests Found:");
						
					}
				
					@Override
					public void handleDBSearchResult(CliMessage dbResult) 
					{	
						ArrayList<TaarifModel>  tReq;
						
						if 	(dbResult!=null)	
						{
							//get a list of all Taarif
							ArrayList<HashMap<String, String>> srs = dbResult.getSrs();
							 tReq= tarRequestModel.getTaarifRequest();
							
						      subGroup=new ArrayList<String>(); 
					    	int rows=srs.size();
						 for(int i = 0 ; i <rows  ; i++)
						 {
							Map<String, String> taarifList  = srs.get(i);	
							
							
							//get gid if subscribed to subscription before
							if(taarifList.get("GID")!=null)
								 subGroup.add(taarifList.get("GID"));
							System.out.println(taarifList.get("GID"));
							System.out.println("size:"+subGroup.size());
							if (subGroup.size()==0)
							{
		                    //add Taarif to arraylist
								
								System.out.println("service id:"+taarifList.get("SERVICEID")+" "+"disc:"+taarifList.get("DESCRIPTION")+" "+"price:"+taarifList.get("PRICE"));
							    tReq.add(new TaarifModel(Integer.parseInt(taarifList.get("SERVICEID")),taarifList.get("DESCRIPTION"),Double.parseDouble(taarifList.get("PRICE")),0));
							
							
							} 					
						 }	
						}
						
						int curruid=up.getCurrUserID();
						
						if (subGroup.size()==0)
						{
						String searchQuery2 = "search"	+"SELECT s.gid "
	                        	+" FROM subreq AS s"
                                +" WHERE s.uid="+ curruid +" AND s.isapprovedbycussrvc=1 AND s.gid IN (SELECT c.subscription_type"
                                +" FROM customer_account AS c"
                                +" WHERE s.uid=c.uid  AND c.active=1"
                                +" GROUP BY c.uid "+")"
                                + " UNION "
			                    + "SELECT s.gid "
	                        	+" FROM subreq AS s"
                                +" WHERE s.uid="+ curruid +" AND s.isapprovedbycussrvc=0";
                                
					
                             
                            sendToServer(searchQuery2);
						}
						if (subGroup.size()!=0)
						{
							//remove subscription if subscribed before
						     tarRequestModel.RemoveTaarif(subGroup);
							tReq=tarRequestModel.getTaarifRequest();
							
							if(tReq.isEmpty())
								SubView.displayWrnMessage("You Have Full Package Subscription");
							
						   //add data from db to combo
						   SubView.setArrayTaarif(tReq);
						   SubView.setCombo();
						   
						 //Set purchase button  listener	
							  setButton();
						
						  
						}
								
				 
						  //display main window
						  SubView.setVisible(true);
			
					}

					@Override
					public void handleNullSearchResult() 
					{
						
				
						//msg
						//SubView.displayWrnMessage("Subscriptions Request Not Found!!!");
						
						subGroup.add("0");
					    handleDBSearchResult(null) ;
						
						
					}

}
